package com.yonyou.pmclouds.personnel.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.personnel.entity.PersonnelRole;
import com.yonyou.pmclouds.personnel.entity.PersonnelSearchConditionVO;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import com.yonyou.pmclouds.personnel.rmiitf.PersonnelMaintain;
import com.yonyou.pmclouds.personnel.rmiitf.PersonnelQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description
 **/
@RestController
@RequestMapping({"/personnel", "/mobile/personnel"})
@Slf4j
public class PersonnelController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private PersonnelQuery personnelQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private PersonnelMaintain personnelMaintain;

    @RequestMapping("/referCheck")
    public boolean checkRef(String pkPersonnel) throws BusinessException {

        return personnelQuery.queryRefCheck(pkPersonnel);

    }

    @RequestMapping("/queryByPkEnterprise")
    public PersonnelVO[] queryByPkEnterprise(@RequestParam("pkEnterprise") String pkEnterprise) throws BusinessException{
        return personnelQuery.queryPersonnelsByPkEtp(pkEnterprise);
    }

    @RequestMapping("/search")
    public PageObject<PersonnelVO> search(@RequestBody PersonnelSearchConditionVO conditionVO) throws BusinessException{
        return personnelQuery.search(conditionVO);
    }

    /**
     *  授权/取消授权 用户
     * @throws BusinessException
     */
    @RequestMapping("/onOffPersonnel")
    @RequiresRoles(value = {PersonnelRole.ENTERPRISE_CONTACT,PersonnelRole.ENTERPRISE_ADMIN},logical = Logical.OR)
    public void onOffPersonnel(@RequestBody PersonnelVO[] personnelVOS,@RequestParam("onOff") String onOff) throws BusinessException{

        personnelMaintain.editOnOffPersonnel(personnelVOS,onOff);

    }

    @RequestMapping("/importFromExcel")
    public PersonnelVO[] importFromExcel(@RequestParam("file") MultipartFile file, String pkEnterprise) throws BusinessException {
        checkImportFromExcel(file);

        List<PersonnelVO> personnelVOS = analyzeExcel(file);

        if ( personnelVOS == null || personnelVOS.isEmpty()) return null;
        for (PersonnelVO personnelVO : personnelVOS) {
            personnelVO.setPkEnterprise(pkEnterprise);
        }

        ArrayList<PersonnelVO> result = personnelMaintain.savePersonnels(personnelVOS.toArray(new PersonnelVO[0]));

        return result.toArray(new PersonnelVO[0]);
    }


    private void checkImportFromExcel(MultipartFile file) throws BusinessException{
        String fileOriName = file.getOriginalFilename();
        if(StringUtils.isEmpty(fileOriName)){
            throw new BusinessException("文件信息不全！");
        }else if(!fileOriName.endsWith(".xls") && !fileOriName.endsWith(".xlsx")){
            throw new BusinessException("导入文件不是Excel格式！");
        }
    }

    /**
     * 解析Excel
     */
    private List<PersonnelVO> analyzeExcel(MultipartFile file) throws BusinessException {
        //导入Excel
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setNeedVerfiy(true);
        params.setKeyIndex(0); //当为空行时不再添加
        ExcelImportResult<PersonnelVO> result;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            result = ExcelImportUtil.importExcelMore(inputStream, PersonnelVO.class, params);
        } catch (Exception e) {
            log.error("人员导入Excel失败：" + e);
            throw new BusinessException("人员导入Excel失败：" + e.getMessage());
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("人员Excel导入关闭输入流失败：" + e);
                }
            }
        }

        if(result == null){
            return new ArrayList<>();
        }

        if(!result.getFailList().isEmpty()){
            StringBuilder errorInfoBuilder = new StringBuilder("如下人员格式编写错误：[");

            for(Object object : result.getFailList()){
                PersonnelVO importVO = (PersonnelVO) object;
                errorInfoBuilder.append(importVO.getSname()).append(",");
            }

            String errorInfo = errorInfoBuilder.toString();
            errorInfo = errorInfo.substring(0, errorInfo.length() - 1) + "],请按限定格式导入。";
            throw new BusinessException(errorInfo);
        }
        return result.getList();
    }

}
